#!/bin/bash
# 定义用法函数
usage() {
  echo "Usage: $0 [-u remote_user] [-i remote_ip] [-p remote_port] [-r remark]"
  echo "Options:"
  echo "  -h, --help    Display this help and exit"
}

# 处理命令行参数
while [[ $# -gt 0 ]]; do
  case "$1" in
    -u|--username)
      remote_user="$2"
      shift 2
      ;;
    -i|--ip)
      remote_ip="$2"
      shift 2
      ;;
    -p|--port)
      remote_port="$2"
      shift 2
      ;;
    -r|--remark)
      remark="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Error: Unknown option '$1'."
      usage
      exit 1
      ;;
  esac
done

# 检查是否提供了必须的参数
if [[ -z "$remote_user" || -z "$remote_ip" || -z "$remote_port" || -z "$remark" ]]; then
  echo "Error: Missing one or more required arguments."
  usage
  exit 1
fi

# 在这里执行脚本的主要操作
if [ ! -f ./remote_info.json ];then
    touch ./remote_info.json
fi

bottom=$(grep -n ']' ./remote_info.json | awk -F':]' '{print $1}')
bottom=${bottom:=0}
if [ $bottom -gt 0 ];then
    sed -i "$bottom"d ./remote_info.json
    sed -i ''''$((bottom-1))'''s/}/},/' ./remote_info.json
else
    echo '[' > ./remote_info.json
fi

cat >> ./remote_info.json <<EOF
    {
        "remote_user": "$remote_user",
        "remote_ip": "$remote_ip",
        "remote_port": "$remote_port",
        "remark": "$remark"
    },
EOF

echo ']' >> ./remote_info.json
sed -i 'x; ${s/.*/    }/;p;x}; 1d' ./remote_info.json